import { useState } from 'react';
import { Plus, X, ChevronDown } from 'lucide-react';
import { useTemplate } from '@/contexts/template';
import { v4 as uuidv4 } from 'uuid';
import type { CheckItemTemplate, CheckItemType } from '@/types/template';

export function ManualAddStep({ onNext }: { onNext: () => void }) {
  const { addItems } = useTemplate();
  const [items, setItems] = useState<Partial<CheckItemTemplate>[]>([
    { id: uuidv4(), title: '', description: '', guide: '', compliance_type: 'risk' as CheckItemType }
  ]);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateItem = (item: Partial<CheckItemTemplate>) => {
    const newErrors: Record<string, string> = {};
    if (!item.title?.trim()) newErrors[`${item.id}-title`] = '请输入标题';
    if (!item.description?.trim()) newErrors[`${item.id}-description`] = '请输入描述';
    if (!item.guide?.trim()) newErrors[`${item.id}-guide`] = '请输入指引内容';
    return newErrors;
  };

  const handleAddItem = () => {
    setItems([...items, { id: uuidv4(), title: '', description: '', guide: '', compliance_type: 'risk' as CheckItemType }]);
  };

  const handleRemoveItem = (_index: number) => {
    if (items.length === 1) return;
    const newItems = [...items];
    newItems.splice(_index, 1);
    setItems(newItems);
  };

  const handleItemChange = (_index: number, field: keyof CheckItemTemplate, value: string | CheckItemType) => {
    const newItems = [...items];
    newItems[_index] = { ...newItems[_index], [field]: value };
    setItems(newItems);
    
    // Clear error for this field if it exists
    const fieldKey = `${newItems[_index].id}-${field}`;
    if (errors[fieldKey]) {
      const newErrors = { ...errors };
      delete newErrors[fieldKey];
      setErrors(newErrors);
    }
  };

  const handleSubmit = () => {
    let hasErrors = false;
    const newErrors: Record<string, string> = {};

    items.forEach((item, _index) => {
      const itemErrors = validateItem(item);
      if (Object.keys(itemErrors).length > 0) {
        hasErrors = true;
        Object.entries(itemErrors).forEach(([key, value]) => {
          newErrors[key] = value;
        });
      }
    });

    setErrors(newErrors);
    if (hasErrors) return;

    // All valid, add to context
    const validItems = items.map(item => ({
      ...item,
      id: item.id || uuidv4(),
      status: 'valid' as const,
    })) as CheckItemTemplate[];

    addItems(validItems);
    onNext();
  };

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <h3 className="text-lg font-medium text-slate-900">手动添加检查项</h3>
        <p className="text-sm text-slate-500">
          填写检查项信息，支持添加多个检查项
        </p>
      </div>

      <div className="space-y-6">
        {items.map((item, _index) => (
          <div key={item.id} className="border border-slate-200 rounded-lg p-4 relative">
            {items.length > 1 && (
              <button
                type="button"
                onClick={() => handleRemoveItem(_index)}
                className="absolute top-2 right-2 text-slate-400 hover:text-slate-600"
                aria-label="移除检查项"
              >
                <X className="h-4 w-4" />
              </button>
            )}
            
            <div className="space-y-4">
              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div className="space-y-2">
                  <label 
                    htmlFor={`title-${item.id}`} 
                    className={`block text-sm font-medium ${
                      errors[`${item.id}-title`] ? 'text-red-600' : 'text-slate-700'
                    }`}
                  >
                    标题 *
                  </label>
                  <input
                    type="text"
                    id={`title-${item.id}`}
                    value={item.title}
                    onChange={(e) => handleItemChange(_index, 'title', e.target.value)}
                    placeholder="例如：密码策略检查"
                    className={`block w-full rounded-md border-0 py-1.5 text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 ${errors[`${item.id}-title`] ? 'ring-red-500' : ''}`}
                  />
                  {errors[`${item.id}-title`] && (
                    <p className="mt-1 text-sm text-red-600">{errors[`${item.id}-title`]}</p>
                  )}
                </div>

                <div className="space-y-2">
                  <label 
                    htmlFor={`type-${item.id}`}
                    className="block text-sm font-medium text-slate-700"
                  >
                    类型 *
                  </label>
                  <div className="relative">
                    <select
                      id={`type-${item.id}`}
                      value={item.compliance_type}
                      onChange={(e) => handleItemChange(_index, 'compliance_type', e.target.value as CheckItemType)}
                      className="block w-full rounded-md border-0 py-1.5 pl-3 pr-10 text-slate-900 ring-1 ring-inset ring-slate-300 focus:ring-2 focus:ring-blue-600 sm:text-sm sm:leading-6 appearance-none"
                    >
                      <option value="risk">风险项</option>
                      <option value="guarantee">保障项</option>
                    </select>
                    <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
                      <ChevronDown className="h-4 w-4 text-slate-500" />
                    </div>
                  </div>
                </div>
              </div>

              <div className="space-y-2">
                <label 
                  htmlFor={`description-${item.id}`}
                  className={`block text-sm font-medium ${
                    errors[`${item.id}-description`] ? 'text-red-600' : 'text-slate-700'
                  }`}
                >
                  描述 *
                </label>
                <div>
                  <textarea
                    id={`description-${item.id}`}
                    rows={2}
                    value={item.description}
                    onChange={(e) => handleItemChange(_index, 'description', e.target.value)}
                    className={`block w-full rounded-md border-0 py-1.5 text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 ${errors[`${item.id}-description`] ? 'ring-red-500' : ''}`}
                    placeholder="请输入检查项描述"
                  />
                  {errors[`${item.id}-description`] && (
                    <p className="mt-1 text-sm text-red-600">{errors[`${item.id}-description`]}</p>
                  )}
                </div>
              </div>

              <div className="space-y-2">
                <label 
                  htmlFor={`guide-${item.id}`}
                  className={`block text-sm font-medium ${
                    errors[`${item.id}-guide`] ? 'text-red-600' : 'text-slate-700'
                  }`}
                >
                  指引内容 *
                </label>
                <div>
                  <textarea
                    id={`guide-${item.id}`}
                    rows={3}
                    value={item.guide}
                    onChange={(e) => handleItemChange(_index, 'guide', e.target.value)}
                    className={`block w-full rounded-md border-0 py-1.5 text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 placeholder:text-slate-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6 ${errors[`${item.id}-guide`] ? 'ring-red-500' : ''}`}
                    placeholder="请输入检查项指引内容"
                  />
                  {errors[`${item.id}-guide`] && (
                    <p className="mt-1 text-sm text-red-600">{errors[`${item.id}-guide`]}</p>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}

        <button
          type="button"
          onClick={handleAddItem}
          className="mt-2 inline-flex items-center px-3 py-1.5 border border-slate-300 shadow-sm text-sm leading-4 font-medium rounded-md text-slate-700 bg-white hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
        >
          <Plus className="-ml-0.5 mr-2 h-4 w-4" />
          添加检查项
        </button>
      </div>

      <div className="flex justify-end space-x-3 pt-4">
        <button
          type="button"
          onClick={() => window.history.back()}
          className="px-4 py-2 border border-slate-300 rounded-md shadow-sm text-sm font-medium text-slate-700 bg-white hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
        >
          取消
        </button>
        <button
          type="button"
          onClick={handleSubmit}
          className="inline-flex justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
        >
          下一步
        </button>
      </div>
    </div>
  );
}
